from hbase import Hbase
from hbase.ttypes import ColumnDescriptor
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
import setting
import HTable

setting.host = '192.168.97.57'


def get_client():
    transport = TSocket.TSocket(setting.host, setting.port)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = Hbase.Client(protocol)
    transport.open()
    return client


def create_table(table_name, columns_str):
    columns = []
    for i in columns_str:
        columns.append(ColumnDescriptor(name=i + ':'))
    get_client().createTable(table_name, columns)


def delete_table(table_name):
    get_client().deleteTable(table_name)


def change_table_name():
    pass


def create_column_family():
    pass


def delete_column_family():
    pass


def change_column_family_name():
    pass


def create_column():
    pass


def delete_column():
    pass


def change_column_name():
    pass


def sync_table():
    for table_name in dir(setting.table_file):
        row = getattr(setting.table_file, table_name)
        '''how to make sure the row's type is a classobj'''
        try:
            if issubclass(row, HTable.BaseTable.Row) and row.__name__ != 'Row':
                obj = row()
                contents = set()
                family_columns = list()
                for i in dir(obj):
                    element = getattr(obj, i)
                    if isinstance(element, HTable.BaseTable.Row.Cell):
                        contents.add(element.family_column() + ':')
                    if isinstance(element, HTable.BaseTable.Row.FixCell):
                        sub_family_columns = list()
                        sub_family_columns.append(ColumnDescriptor(name=str(table_name).lower()+':'))
                        sub_family_columns.append(ColumnDescriptor(name=str(element.table_name()).lower()+':'))
                        sub_family_columns.append(ColumnDescriptor(name='status:'))
                        get_client().createTable(table_name+element.table_name(), sub_family_columns)
                for i in contents:
                    family_columns.append(ColumnDescriptor(name=i))
                family_columns.append(ColumnDescriptor(name='status:'))
                get_client().createTable(table_name, family_columns)
        except TypeError:
            continue
    print 'sync success'


sync_table()
